package cn.sfa.controller.prospectus;

import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import cn.sfa.common.pagination.Pagination;
import cn.sfa.common.taglib.CommonCache;
import cn.sfa.common.utils.CommonUtil;
import cn.sfa.common.utils.MajorKeyGenerate;
import cn.sfa.common.utils.TableNameEnum;
import cn.sfa.common.utils.WebInitBinderContoller;
import cn.sfa.entity.affixItem.SaleAffixItem;
import cn.sfa.entity.prospectus.SaleProspectus;
import cn.sfa.entity.system.BranchSysCode;
import cn.sfa.entity.system.ProviderSysCode;
import cn.sfa.entity.users.SaleUsersLogin;
import cn.sfa.service.affix.AffixService;
import cn.sfa.service.product.ProductService;
import cn.sfa.service.prorsectus.ProspectusService;

/**
 * 供应商计划书
 * 
 * @author hui
 * 
 */
@Controller
@RequestMapping("productandtrain/prospectus/index")
public class ManageProspectusController extends WebInitBinderContoller {

	Logger log = Logger.getLogger(ManageProspectusController.class);
	@Autowired
	private ProspectusService prospectusService;
	@Autowired
	MajorKeyGenerate majorKeyGenerate;
	@Autowired
	AffixService affixService;
	@Autowired
	ProductService productService;

	@RequestMapping
	public String index(
			@RequestParam(value = "currentPage", required = false) String currentPage,// 页码
			@RequestParam(value = "planbookname", required = false) String planbookname,// 计划书名称
			@RequestParam(value = "providername", required = false) String providername,// 供应商名称
			@RequestParam(value = "productname", required = false) String productname,// 产品名称
			@RequestParam(value = "branchId", required = false) String branchId,// 机构id
			HttpServletRequest request, ModelMap map,
			HttpServletResponse response) {
		SaleUsersLogin user = (SaleUsersLogin) request.getSession()
				.getAttribute("user");
		String loginbranchId = user.getBranchId();
		String productSupplier = "";
		String providerStr = "";
		if(providername != null){ 
			productSupplier = providername.substring(providername.indexOf(":")+1,providername.length());
			providerStr = productSupplier ;
			if(productSupplier.lastIndexOf("(") > -1){
				providerStr = productSupplier.substring(0,productSupplier.lastIndexOf("("));
				 
				}
			}
		System.out.println("-------------------------------");
		System.out.println(providerStr);
		int pageIndex;
		try {
			pageIndex = Integer.valueOf(currentPage);
		} catch (Exception ex) {
			pageIndex = 1;
		}
		String url = request.getContextPath()
				+ "/productandtrain/prospectus/index?" + "productname="
				+ CommonUtil.jugeAndFixNull(productname) + "&providerStr="
				+ CommonUtil.jugeAndFixNull(providerStr)  + "&branchId="
				+ CommonUtil.jugeAndFixNull(branchId);
		Pagination pagination = prospectusService.seachProspectus(pageIndex,
				10, url, planbookname, providerStr, productname, branchId);
		map.put("pagination", pagination);
		map.put("planbookname", planbookname);
		map.put("providername", providername);
		map.put("productname", productname);
		map.put("providerStr", providerStr);
		map.put("branchId", branchId);
		List<BranchSysCode> list = null;
		map.put("BranchList", list);
		return "productandtrain/prospectus/index";

	}

	/**
	 * 
	 * @param request
	 * @param map
	 * @param response
	 * @return
	 */
	@RequestMapping("/add")
	public String add(HttpServletRequest request, ModelMap map,
			HttpServletResponse response) {
		SaleUsersLogin user = (SaleUsersLogin) request.getSession()
				.getAttribute("user");
		List<ProviderSysCode> providerList = prospectusService
				.getProviderAutoCompleteList();
		List<BranchSysCode> list = null;
		map.put("BranchList", list);
		map.put("providerList", providerList);

		return "productandtrain/prospectus/add";

	}

	/**
	 * AJAX新增计划书
	 * 
	 * @param affixStr
	 * @param vildstartdate
	 * @param vildstopdate
	 * @param provider
	 * @param request
	 * @param model
	 * @param response
	 * @param map
	 * @throws Exception
	 */
	@RequestMapping("/insert")
	public void insert(
			@RequestParam(value = "affixStr", required = false) String affixStr,
			@RequestParam(value = "vildstartdate", required = false) String vildstartdate,
			@RequestParam(value = "vildstopdate", required = false) String vildstopdate,
			@RequestParam(value = "provider", required = false) String provider,
			HttpServletRequest request, SaleProspectus model,
			HttpServletResponse response, ModelMap map) throws Exception {
		String productName = request.getParameter("productName");
		String productCode = request.getParameter("productCode");
		String providerid = provider.substring(0, provider.indexOf("|"));
		String providername = provider.substring(provider.indexOf("|") + 1,
				provider.length());
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		Date vildStartDate = dateFormat.parse(vildstartdate);
		Date vildStopDate = dateFormat.parse(vildstopdate);
		// 设置主键
		model.setSaleprospectusid(majorKeyGenerate
				.keyGenerate(TableNameEnum.SALEPROVIDERPLANBOOK));

		// 设置creatuser
		SaleUsersLogin user = (SaleUsersLogin) request.getSession()
				.getAttribute("user");
		model.setCreateUid(user.getSaleUsersLoginId());
		model.setVildstartdate(vildStartDate);
		model.setVildstopdate(vildStopDate);
		model.setProviderid(providerid);
		model.setProvidername(providername);
		model.setProductCode(productCode);
		model.setProductname(productName);
		if (affixStr.equals(" ") || affixStr.length() == 0) {
			model.setIsAffix("N");
		} else {
			model.setIsAffix("Y");
		}

		if (vildStopDate.getTime() - vildStartDate.getTime() < 0) {
			out.print("{result:false,message:'有效时间始必须大于有效时间止 !'}");
			out.flush();
			out.close();
			return;
		}

		try {
			boolean result = prospectusService.insertProspectus(model); 
			if (result = true) {
				affixService.saveAffix(affixStr, "SALEPROVIDERPLANBOOK", model.getSaleprospectusid());
				out.print("{result:true,message:'新增成功!'}");
			} else {
				out.print("{result:false,message:'新增失败!!'}");
			}
		} catch (Exception e) {
			log.info("==============" + e.getMessage());
			out.print("{result:false,message:'修改失败!!'}");
		}
		out.flush();
		out.close();
	}

	/**
	 * 修改计划书
	 * 
	 * @param request
	 * @param map
	 * @param response
	 * @return
	 */
	@RequestMapping("/edit/{saleproviderplanbookid}")
	public String edit(
			@PathVariable("saleproviderplanbookid") String saleproviderplanbookid,
			HttpServletRequest request, ModelMap map,
			HttpServletResponse response) {
		SaleUsersLogin user = (SaleUsersLogin) request.getSession()
				.getAttribute("user");
		SaleProspectus prospectus = prospectusService
				.getPlanBookByID(saleproviderplanbookid);
		
		List<BranchSysCode> list = null;
		List<ProviderSysCode> providerList = prospectusService
				.getProviderAutoCompleteList();
		List<SaleAffixItem> affixList = affixService.getAffix(
				"SALEPROVIDERPLANBOOK", saleproviderplanbookid);
		map.put("saleproviderplanbookid", saleproviderplanbookid);
		map.put("BranchList", list);
		map.put("affixList", affixList);
		map.put("prospectus", prospectus);
		map.put("providerList", providerList);
		return "productandtrain/prospectus/edit";
	}
	/**
	 * AJAX修改
	 * @param saleproviderplanbookid
	 * @param affixStr
	 * @param vildstartdate
	 * @param vildstopdate
	 * @param provider
	 * @param request
	 * @param model
	 * @param response
	 * @param map
	 * @throws Exception
	 */
	@RequestMapping("/update")
	public void update(
			@RequestParam(value = "saleproviderplanbookid", required = false) String saleproviderplanbookid,
			@RequestParam(value = "affixStr", required = false) String affixStr,
			@RequestParam(value = "vildstartdate", required = false) String vildstartdate,
			@RequestParam(value = "vildstopdate", required = false) String vildstopdate,
			@RequestParam(value = "provider", required = false) String provider,
			HttpServletRequest request, SaleProspectus model,
			HttpServletResponse response, ModelMap map) throws Exception {
		String productCode = request.getParameter("productCode");
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		String providerid = provider.substring(0, provider.indexOf("|"));
		String providername = provider.substring(provider.indexOf("|") + 1,
				provider.length());
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		Date vildStartDate = dateFormat.parse(vildstartdate);
		Date vildStopDate = dateFormat.parse(vildstopdate);
		SaleUsersLogin user = (SaleUsersLogin) request.getSession()
				.getAttribute("user");
		
		model.setSaleprospectusid(saleproviderplanbookid);
		model.setUpdateUser(user.getSaleUsersLoginId());
		model.setVildstartdate(vildStartDate);
		model.setProductCode(productCode);
		model.setVildstopdate(vildStopDate);
		model.setProviderid(providerid);
		model.setProvidername(providername);
		if (affixStr.equals(" ") || affixStr.length() == 0) {
			model.setIsAffix("N");
		} else {
			model.setIsAffix("Y");
		}
		
		if (vildStopDate.getTime() - vildStartDate.getTime() < 0) {
			out.print("{result:false,message:'有效时间始必须大于有效时间止 !'}");
			out.flush();
			out.close();
			return;
		}
		try{
			boolean result = prospectusService.updateProspectus(model);
			if (result = true) {
				affixService.saveAffix(affixStr, "SALEPROVIDERPLANBOOK", saleproviderplanbookid);
				out.print("{result:true,message:'修改成功!'}");
			} else {
				out.print("{result:false,message:'修改失败!!'}");
			}
		}catch (Exception e) {
			
		}
	}
	/**
	 * 删除计划书
	 * @param saleproviderplanbookid
	 * @param request
	 * @param response
	 * @param map
	 * @throws Exception
	 */
	@RequestMapping("/del/{saleproviderplanbookid}")
	public void delete(@PathVariable("saleproviderplanbookid") String saleproviderplanbookid,
			HttpServletRequest request, HttpServletResponse response,
			ModelMap map) throws Exception {
  System.out.println(saleproviderplanbookid);
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		String result;
		try {
			result = prospectusService.delProspectus(saleproviderplanbookid) ? "true" : "false";
		} catch (Exception ex) {
			log.info("==============" + ex.getMessage());
			result = "false";
		}
		out.print(result);
		out.flush();
		out.close();
	}
	
	/**
	 * 计划书信息
	 * @param saleproviderplanbookid
	 * @param request
	 * @param map
	 * @param response
	 * @return
	 */
	@RequestMapping("/info/{saleproviderplanbookid}")
	public String info(	
			@PathVariable("saleproviderplanbookid") String saleproviderplanbookid,
			HttpServletRequest request, ModelMap map,
			HttpServletResponse response){
		SaleProspectus prospectus = prospectusService.getPlanBookByID(saleproviderplanbookid);
		List<SaleAffixItem> affixList = affixService.getAffix("SALEPROVIDERPLANBOOK", saleproviderplanbookid);
		map.put("affixList", affixList);
		map.put("prospectus", prospectus);
		return "productandtrain/prospectus/info";
	}
}
